package top.yj95.xiets.basic;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import javax.swing.WindowConstants;

/**
 * 文章《<a href="https://xiets.blog.csdn.net/article/details/74363751" target="_balnk">JavaSwing_2.11: JProgressBar（进度条）</a>》中的示例代码
 * @author 杨军
 * @since 2023-12-25
 */
public class JProgressBarDemo {
    
    private static final int MIN_PROGRESS = 0;
    
    private static final int MAX_PROGRESS = 100;
    
    private static int currentProgress = MIN_PROGRESS;
    
    public static void main(String[] args) {
        JFrame frame = new JFrame("测试窗口");
        frame.setSize(250, 200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        JPanel panel = new JPanel();
        
        // 创建一个进度条
        JProgressBar progressBar = new JProgressBar();
        
        // 设置进度条的 最小值 和 最大值
        progressBar.setMinimum(MIN_PROGRESS);
        progressBar.setMaximum(MAX_PROGRESS);
        
        // 设置当前进度值
        progressBar.setValue(currentProgress);
        
        // 绘制百分比（进度条中间显示百分数）
        progressBar.setStringPainted(true);
        
        // 添加进度条改变通知
        progressBar.addChangeListener(e -> System.out.printf("当前进度值：%d；进度百分比：%f\n", 
            progressBar.getValue(), progressBar.getPercentComplete()));
        
        // 添加到内容面板
        panel.add(progressBar);
        
        frame.setContentPane(panel);
        frame.setVisible(true);
        
        // 模拟延时操作，每隔 0.5秒 更新进度
        new Timer(500, e -> {
            ++currentProgress;
            if (currentProgress > MAX_PROGRESS) {
                currentProgress = MIN_PROGRESS;
            }
            progressBar.setValue(currentProgress);
        }).start();
    }
    
}
